package cn.kimming.rpc.remoting.serialization;

import java.io.*;

public class JDKSerialization implements ISerialization{

    private static JDKSerialization instance = new JDKSerialization();

    public static JDKSerialization getInstance() {
        return instance;
    }

    @Override
    public <T> byte[] serialize(T obj) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)){
            oos.writeObject(obj);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return baos.toByteArray();
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> cls) {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        Object object = null;
        try (ObjectInputStream ois = new ObjectInputStream(bais)) {
            object = ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return (T)object;
    }
}
